// pages/list/list.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    listData: [], //菜单分类
    activeIndex: 0,//菜单高亮
    activeFlag:false,//菜单高亮flag
    toView: 'a0',//滚动到哪个分类 -设置菜单往哪个方向滚动
    scrollTop: 100, //点击菜单没类时,竖向滚动条位置
    screenWidth: 667,//??没用到
    showModalStatus: false,//选料温度..模态框
    currentType: 0, //当前菜单分类
    currentIndex: 0,//当前菜单分类下序号
    sizeIndex: 0,//杯型分类序号
    sugarIndex: 0,//甜度分类序号
    temIndex: 0,//温度分类序号
    sugar: ['正常糖', '少糖', '半糖'],
    tem: ['正常冰', '少冰', '去冰'],
    size: ['常规', '珍珠', '西米露'],
    cartList: [],//购物车
    sumMonney: 0,//总金额
    cupNumber: 0,//总杯数
    scrollH: 1000, //动态计算菜单高度
    showCart: false,//是否显示购物车
    // loading: false,//列表数据获取成功 展示购物车栏(目前放弃该功能)
    cartMap: {},//购物车map
    model: 0,//1是预约模式  0是到店模式
    appointTime: "",//预约取餐时间
    scrollArr: [],//[0,237,474] 用于计算滚动距离(左边跟随右边滚动)
    sizeBox: [],//存放每次添加商品时的 加料
    sizeEx: 0//加料金额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.model)
    console.log(options.appointTime)
    //当为预约取餐时 赋值取餐时间
    if (options.model == 1) {
      this.setData({
        model: 1,
        appointTime: options.appointTime
      })
    }
    var that = this;
    this.getList()
  },
  //获取菜单列表
  getList() {
    var that = this;
    //获取可使用窗口高度，单位px
    var sysinfo = wx.getSystemInfoSync().windowHeight;
    // console.log(sysinfo)
    // wx.showLoading({
    // })
    // let offsetS = 120
    // //兼容iphoe5滚动
    // if (sysinfo < 550) {
    //   offsetS = -40
    // }
    // //兼容iphoe Plus滚动
    // if (sysinfo > 650 && sysinfo < 700) {
    //   offsetS = 240
    // }
    wx.request({
      url: app.globalData.apiHost + '/getfoodList',
      method: 'GET',
      data: {},
      header: {
        'Accept': 'application/json'
      },
      success: function (res) {
        let scrollArr = [0]
        //动态计算联动节点(左边跟随右边滚动)
        for (let i = 0; i < res.data.data.length; i++) {
          // console.log(res.data.data[i].foods.length)
          scrollArr.push(scrollArr[i] + 73 * res.data.data[i].foods.length + 18)        
        }
        console.log(res.data.data);
        that.setData({
          scrollArr: scrollArr,
          listData: res.data.data,
          // loading: true,
          scrollH: sysinfo * 2
        })
        wx.hideLoading();
      }
    })
  },
  // 左侧菜单分类点击
  selectMenu: function (e) {
    var index = e.currentTarget.dataset.index
    // console.log(index)
    this.setData({
      activeIndex: index, //菜单分类高亮
      toView: 'a' + index, //滚动到哪个分类
      activeFlag:true
    })
  },
  //监听滚动<scroll-view> 完成右到左的联动
  scroll: function (e) {
    //如果是点击分类触发的则不需要执行该方法
    if(this.data.activeFlag){
      this.setData({
        activeFlag:false
      })
      return;
    }
    var dis = e.detail.scrollTop;
    for (let i = 0; i < this.data.scrollArr.length; i++) {
      if (i < this.data.scrollArr.length - 1) {//未超过计算高亮哪一个
        //滚动距离在scrollArr的[i]跟[i+1]直接时高亮[i]
        if (dis+i > this.data.scrollArr[i] && dis+i < this.data.scrollArr[i + 1]) {
          // 设置高亮
          this.setData({
            activeIndex: i,
          })
          break;
        }
      } else {//超过默认高亮最后一个
        this.setData({
          activeIndex: this.data.scrollArr.length - 1,
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  // 点击加购
  selectInfo: function (e) {
    var type = e.currentTarget.dataset.type; //属于菜单第几个分类
    var index = e.currentTarget.dataset.index; //属于分类中第几个 0开始
    var a = this.data;
    var tem = a.listData[type].foods[index].tem; //温度选择
    var temBox = []; //存放温度选择
    for (let i = 0; i < tem.length; i++) {
      temBox.push(tem[i].specs)
    }
    this.setData({
      showModalStatus: !this.data.showModalStatus,//选料温度模态框
      currentType: type, //当前菜单分类
      currentIndex: index, //当前菜单分类下序号
      sizeBox: ["常规"],
      sizeEx: 0,
      sugarIndex: 0,//甜度分类序号
      temIndex: 0, //温度分类序号
      tem: temBox
    });
  },
  //关闭选料温度模态框
  closeModal: function () {
    this.setData({
      showModalStatus: false
    });
  },
  //加购时-加料?糖度?温度选择
  chooseSE: function (e) {
    var a = this.data.listData;
    var index = e.currentTarget.dataset.index; //选择第几个料?糖?温?
    
    console.log(a);console.log(index);
    var type = e.currentTarget.dataset.type; //选的是加料?糖度?温度?
    if (type == 0) {//加料
      var item = a[this.data.currentType].foods[this.data.currentIndex].size; //加料选择
      var sizeBox = this.data.sizeBox;
      var sizeEx = this.data.sizeEx;
      console.log(item[index].packing_fee);
      //加料 1 选择, 0 取消
      //常规 默认packing_fee == 1,其他默认为 0
      if (item[index].packing_fee == 0) {
        console.log(123);
        item[index].packing_fee = 1 //修改为选择状态
        sizeBox.push(item[index].specs) //存放加料
        sizeEx += item[index].price //加料后金额增加
      } else { //取消加料
        console.log(456);
        item[index].packing_fee = 0//修改为未选择状态
        //去除选择的料&减去金额
        for (let i = 0; i < sizeBox.length; i++) {
          if (sizeBox[i] == item[index].specs) {
            sizeBox.splice(i, 1)
            sizeEx -= item[index].price
          }
        }
      }
      this.setData({
        listData: a,
        sizeBox: sizeBox,
        sizeEx: sizeEx
      });
    }
    if (type == 1) {//糖度
      this.setData({
        sugarIndex: index
      });
    }
    if (type == 2) {//温度
      this.setData({
        temIndex: index
      });
    }
  },  
  //查看是否添加过相同规格的商品
  isSameAdd: function () {
    var a = this.data
    var name = a.listData[a.currentType].foods[a.currentIndex].name; //选择食品名
    var cartList = this.data.cartList;//购物车
    var detail = '';//料+糖+温的明细
    //加料写入明细
    for (let i = 0; i < a.sizeBox.length; i++) {
      detail += a.sizeBox[i] + ","
    }
    //料+糖+温的明细
    detail = detail.substring(0,detail.length-1) + "+" + a.sugar[a.sugarIndex] + "+" + a.tem[a.temIndex];
    //查看添加的是否与购物车里的相同(名&明细)
    for (var i = 0; i < cartList.length; i++) {
      console.log(detail);
      //cartList[i].detail & detail 常规,象丸,西米+正常糖+正常冰
      if ((name == cartList[i].name) && (detail == cartList[i].detail)) {
        return i
      }
    }
  },
  //加入购物车
  addToCart: function () {
    var a = this.data
    var listData = a.listData;
    var cartList = this.data.cartList;//购物车
    //查看是否添加过相同规格的商品
    if (this.isSameAdd() != undefined) {
      // console.log("添加过")
      //同个商品number+1
      cartList[this.isSameAdd()].number += 1
    } else {
      // console.log("没加过")
      var detail = "";
      //加料写入明细
      for (let i = 0; i < a.sizeBox.length; i++) {
        detail += a.sizeBox[i] + ","
      }
      //去掉加料最后一个逗号
      detail=detail.substring(0,detail.length-1)

      var addItem = {
        "cType": a.currentType,//当前菜单分类
        "cIndex": a.currentIndex,//当前菜单分类下序号
        "name": a.listData[a.currentType].foods[a.currentIndex].name,
        "price": a.listData[a.currentType].foods[a.currentIndex].price + a.sizeEx,//总金额(本身+加料)
        "enName": a.listData[a.currentType].foods[a.currentIndex].enName,
        "detail": detail + "+" + a.sugar[a.sugarIndex] + "+" + a.tem[a.temIndex],//料+糖+温
        "number": 1,
        "sum": a.listData[a.currentType].foods[a.currentIndex].price + a.sizeEx,//总金额(本身+加料) 跟上边相同?
        // "img": a.currentType + 1 + "-" + a.listData[a.currentType].foods[a.currentIndex].img,//图片
        "img": a.listData[a.currentType].foods[a.currentIndex].img,
        "desc": a.listData[a.currentType].foods[a.currentIndex].desc//???
      }
      cartList.push(addItem);
    }

      //恢复加料默认都不选中
      var item = listData[a.currentType].foods[a.currentIndex].size; //加料选择
      for (let i = 0; i < item.length; i++) {
        item[i].packing_fee = 0;
      }

    //刷新总金额
    var sumMonney = a.sumMonney + a.listData[a.currentType].foods[a.currentIndex].price + a.sizeEx;
    //刷新单品杯数
    listData[a.currentType].foods[a.currentIndex].num += 1
    this.setData({
      cartList: cartList,
      showModalStatus: false,
      sumMonney: sumMonney,
      cupNumber: a.cupNumber + 1,
      listData: listData
    });
  },
  //显示购物车详情
  showCartList: function () {
    console.log(this.data.showCart)
    if (this.data.cartList.length != 0) {
      this.setData({
        showCart: !this.data.showCart,
      });
    }

  },
  // 清空购物车
  clearCartList: function () {
    var listData = this.data.listData;
    //将菜单列表的餐品数量都改为0
    for(let i=0;i<listData.length;i++){
      for(let j=0;j<listData[i].foods.length;j++){
        listData[i].foods[j].num=0;
      }
    };
    this.setData({
      cartList: [],
      showCart: false,
      sumMonney: 0,
      listData:listData,
      cupNumber:0
    });
    console.log(this.data.cartList);
    console.log(this.data.listData);
  },
  // 购物车中的加购
  addNumber: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var cartList = this.data.cartList;
    var listData = this.data.listData
    console.log(listData[cartList[index].cType].foods[cartList[index].cIndex].num)
    listData[cartList[index].cType].foods[cartList[index].cIndex].num = listData[cartList[index].cType].foods[cartList[index].cIndex].num + 1
    cartList[index].number++;
    var sum = this.data.sumMonney + cartList[index].price;
    cartList[index].sum += cartList[index].price;
    this.setData({
      listData: listData,
      cartList: cartList,
      sumMonney: sum,
      cupNumber: this.data.cupNumber + 1
    });
  },
  // 购物车中的减购
  decNumber: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var cartList = this.data.cartList;
    var listData = this.data.listData
    listData[cartList[index].cType].foods[cartList[index].cIndex].num = listData[cartList[index].cType].foods[cartList[index].cIndex].num - 1
    var sum = this.data.sumMonney - cartList[index].price;
    cartList[index].sum -= cartList[index].price;
    cartList[index].number == 1 ? cartList.splice(index, 1) : cartList[index].number--;
    this.setData({
      listData: listData,
      cartList: cartList,
      sumMonney: sum,
      showCart: cartList.length == 0 ? false : true, //0时关闭购物车
      cupNumber: this.data.cupNumber - 1
    });
  },
  goBalance: function () {
    if (this.data.sumMonney != 0) {
      wx.setStorageSync('cartList', this.data.cartList); //选购商品明细
      wx.setStorageSync('sumMonney', this.data.sumMonney); //总金额
      wx.setStorageSync('cupNumber', this.data.cupNumber); //总数量
      //跳转到结账页面
      //model: 0,//1是预约模式  0是到店模式
      //appointTime取餐时间
      wx.navigateTo({
        url: '../order/balance/balance?model=' + this.data.model + "&appointTime=" + this.data.appointTime
      })
    }
  },
  //减购提示
  notice: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '因含有规格，请在购物车内删减',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          that.setData({
            showCart: true
          });
        }
      }
    })
  },
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})